//
//  UploadFileViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/31.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "UploadFileViewController.h"
#import "RentVieitor.h"
#import "UIImageView+WebCache.h"

@interface UploadFileViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end

@implementation UploadFileViewController {
    
    UIImageView *editView;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"上传证明材料";
    self.view.backgroundColor = BackgroundColor;
    [self creatView];
    [self creatLeftView];
    
}

- (void)returnImgBlock:(SelectImgBlock)block {
    
    self.selecImgBlock = block;
}
- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 100,15 );
    [leftBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"经纪人认证" forState:UIControlStateNormal];
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [leftBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 50, 20);
    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(sumbitAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)creatView {
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, KWidth, 30)];
    textLabel.text = [NSString stringWithFormat:@"你需要上传所属中介公司证明材料"];
    textLabel.textColor = [Utils colorConvertFromString:@"#666666"];
    textLabel.font = [UIFont boldSystemFontOfSize:13];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.numberOfLines = 0;
    [self.view addSubview:textLabel];

    editView = [[UIImageView alloc] initWithFrame:CGRectMake((KWidth-200)/2, 50, 200, 150)];
    if (self.fileImg != nil) {
        [editView sd_setImageWithURL:[NSURL URLWithString:self.fileImg]];
    }else {
        editView.image = [UIImage imageNamed:@"上传按钮"];
    }
   
    editView.userInteractionEnabled = YES;
    editView.tag = 100;
    [self.view addSubview:editView];

    //添加手势
    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
    [editView addGestureRecognizer:PrivateLetterTap];

    
}

- (void)tapAvatarView:(UIGestureRecognizer*)reconger{
    
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            // 跳转到相机页面
            UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            //            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self.navigationController presentViewController:imagePickerController animated:YES completion:NULL];
        }
        
        
        
    }];
    
    
    UIAlertAction *picAlbumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //跳转到相册
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        //        [self presentModalViewController:pickerImage animated:YES];
        [self.navigationController presentViewController:pickerImage animated:YES completion:NULL];
        
        
    }];
    
    UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertVC addAction:photoAction];
    [alertVC addAction:picAlbumAction];
    [alertVC addAction:canceAction];
    [self presentViewController:alertVC animated:YES completion:NULL];
    
}

#pragma mark -- 成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]) {
        
        //获取照片的原图
        UIImage *original = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //将图片大小压缩
//        UIImage *samllImg = [self scaleImage:original toKb:400];
         UIImage *samllImg = [self imageCompressForWidthScale:original targetWidth:500];
        
        //NSData * imageData2 = UIImageJPEGRepresentation(samllImg,0.9f);
        //long length2 = [imageData2 length]/1024.0f;
        // NSLog(@"压缩后大小%ldKB",length2);
        
        [self uploadFile:samllImg Withkey:nil];
        
        
//        //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
//        UIImageWriteToSavedPhotosAlbum(samllImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
        //        NSURL *picurl=[info objectForKey:UIImagePickerControllerReferenceURL];
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

-(UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    
    kb*=1024;
    
    
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
    
    
    
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)uploadFile:(UIImage *)img Withkey:(NSString *)key{
    
    if (img == nil) {
        return;
    }
    NSData *fileData = UIImageJPEGRepresentation(img, 1.0f);
    NSString *fieleImageStr = [fileData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *dataDic = User_listsValue;
    NSString *url = [NSString stringWithFormat:@"%@agent/upload",Main_Url];
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSDictionary *dic = @{
                          @"number":number,
                          @"token":token,
                          @"img":fieleImageStr
                          };
    __weak __typeof(self)weakSelf = self;
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    //    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSDictionary *dataArray = response[@"data"];
            NSString *dicKey = dataArray[@"path"];
            if (dicKey != nil) {
                //将图片保存至字典
                weakSelf.fileImg = dicKey;
                editView.image = img;
            }
            
        }else {
            
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        
    }];
    
    
    //    if (self.selecImgBlock != nil) {
    //        self.selecImgBlock(editView.image);
    //    }
    //    [self.navigationController popViewControllerAnimated:YES];
}


- (void)sumbitAction {
    
    if (editView.image == nil) {
        
        [APPDELEGATE showPro:@"请选择照片"];
        return;
    }
    
    if ( [self.fileImg isEqualToString:@""]) {
        
        [APPDELEGATE showPro:@"图片上传中"];
        return;
    }
    
    if (self.selecImgBlock != nil) {
        self.selecImgBlock(self.fileImg);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark 图片压缩
-(UIImage *) imageCompressForWidthScale:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}



@end
